package com.lagou.handler;

import com.lagou.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware  {

    private static ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        if(msg instanceof RpcRequest){

            RpcRequest rpcRequest = (RpcRequest)msg;

            Object bean = applicationContext.getBean(lowerFirst(rpcRequest.getClassName()));

            Method method = bean.getClass().getMethod(rpcRequest.getMethodName(),rpcRequest.getParameterTypes());
            String result = (String)method.invoke(bean,rpcRequest.getParameters());


            ctx.writeAndFlush(result);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public String lowerFirst(String fromStr){
        char[] chars = fromStr.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
